#include "sObserver.h"
#include <algorithm>

namespace sgui
{
namespace obs
{

const EEventId sEvent::getID() const
{ 
	return EVID_NONE; 
};

const EEventType sEvent::getType() const
{ 
	return EVTYPE_UNKNOWN; 
};

void sSubject::registerObserver(sObserver* observer, const EEventTag tag /* = EVTAG_ALL */)
{
	sSubjectObserver sobs;

	sobs.m_observer = observer;
	sobs.m_tag = tag;

	std::vector<sSubjectObserver>::iterator it = std::find(m_observers.begin(), m_observers.end(), sobs);
	if (it == m_observers.end())
	{
		m_observers.push_back(sobs);
	}
}
	
void sSubject::unregisterObserver(sObserver* observer, bool andRelease /* = false */)
{
	std::vector<sSubjectObserver>::iterator it = std::find_if(m_observers.begin(), m_observers.end(), 
		[observer](const sSubjectObserver& fnd) -> bool{
			return fnd.m_observer == observer;
		});
	if (it != m_observers.end())
	{
		if (andRelease)
			delete it->m_observer;
		m_observers.erase(it);
	}
}
	
void sSubject::notify(sEvent* event, const EEventTag tag /* = EVTAG_ALL */)
{
	if (tag == EVTAG_ALL)
	{
		for (unsigned int i = 0, t = m_observers.size(); i < t; i++)
		{
			if (m_observers[i].m_observer->OnEvent(*event)) break;
		}
	}
	else
	{
		for (unsigned int i = 0, t = m_observers.size(); i < t; i++)
		{
			if (m_observers[i].m_tag == tag && m_observers[i].m_tag == EVTAG_ALL)
				if (m_observers[i].m_observer->OnEvent(*event)) break;
		}
	}
	delete event;
}

};
};